import datetime
from django.core.exceptions import ObjectDoesNotExist
from django_filters.rest_framework import DjangoFilterBackend
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.decorators import action, permission_classes
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

import backend.permissions
from backend import helper
from posts.filters import PostFilter
from posts.models import Post
from posts.permissions import PostPermission
from posts.serializers import PostSerializer


@permission_classes([PostPermission,
                     backend.permissions.IsManualAuthenticatedOrReadOnly])
class PostViewSet(helper.MyModelViewSet):
    """
    帖子接口，需要权限。
        1. 'Basic Auth'
        2. JWT认证，请求头Authorization：JWT + 登陆返回的Token
    """
    # 最新的帖子
    queryset = Post.objects.all().order_by('-created_at')
    serializer_class = PostSerializer

    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filter_class = PostFilter

    ordering_fields = ['created_at', 'likes', 'annotation']
    search_fields = ['=author__username', 'category', 'title']

    @action(methods=['POST'], detail=True,
            permission_classes=[IsAuthenticated])
    def thumbs_up(self, request, pk):
        """
        未实名和实名用户均可点赞。
        通过<pk>索引，对指定帖子点赞。
        暂时没有限制点赞次数（一个人可以让点赞数不停增加，maybe前端考虑限制一次，还要实现throttle）
        """
        instance = Post.objects.get(id=pk)
        if not instance:
            raise ObjectDoesNotExist()

        instance.likes += 1
        instance.save(update_fields=['likes'])

        return Response(data={
            "success": True,
            "code": 200,
            "msg": "点赞成功",
            "likes": instance.likes,
        }, status=status.HTTP_200_OK)

    @action(methods=['POST'], detail=True,
            permission_classes=[IsAuthenticated])
    def add_history(self, request, **kwargs):
        post_id = kwargs.get('pk')
        instance = Post.objects.get(id=post_id)
        user_id = request.data.get('id')
        if not instance:
            raise ObjectDoesNotExist()

        redis_con = get_redis_connection('default')
        history_key = 'posts_history_%s' % user_id  # 拼接出key
        get_CST_time_in_ISO_format = datetime.datetime.now().isoformat()
        history_value = {
            'post_id': post_id,
            'time': get_CST_time_in_ISO_format,
        }
        # 每次插入前都删除以前的历史记录,
        post_datas = redis_con.lrange(history_key, 0, 50)
        for i in range(len(post_datas)):
            if str(b"{'post_id': '%d'" % int(post_id)) in \
                    str(post_datas[i]).split(',', 1)[0]+"\"":
                redis_con.lrem(history_key, i, post_datas[i])
                break
        redis_con.lpush(history_key, str(history_value))
        redis_con.ltrim(history_key, 0, 50)
        return Response(data={
            "success": True,
            "code": 200,
            "msg": "添加贴子历史记录成功",
            "user": user_id,
            "data": history_value,
        }, status=status.HTTP_200_OK)
